/*
 * @Description: 
 * @Author: YangHeng
 * @Date: 2021-08-11 18:42:20
 * @FilePath: \web_server_app\mongoose\static.js
 */
const mongoose = require('mongoose');

module.exports = class StaticDb {
  /**
   * @description: 获取ObjectId
   * @param {ObjectId|string} id
   * @return {ObjectId}
   */
  objId(id) {
    const _id = mongoose.Types.ObjectId(id);
    return _id;
  }
  /**
   * @description: 通过ID获取数据
   * @param {ObjectId|string} id
   */
  async getId (id) {
    const doc = await this.findById(id)
    return doc;
  }
  /**
   * @description: 添加数据
   * @param {Object} data 
   */
  async add (data) {
    const doc = new this(data);
    const _doc = await doc.save();
    return _doc;
  }
  /**
   * @description: 添加多条数据
   * @param {Array} list
   */
  async addList (list) {
    const docs = await this.insertMany(list);
    return docs;
  }
  /**
   * @description: 删除数据
   * @param {*} id
   */
  async del (id) {
    await this.findByIdAndRemove(id);
  }
  /**
   * @description: 修改数据
   * @param {*} data
   */
  async edit (data) {
    const id = data._id;
    delete data._id;
    const newData = await this.findByIdAndUpdate(id, {$set: data}, {new: true});
    return newData;
  }
  /**
   * @description: 获取列表
   * @param {*} json 查询条件
   * @param {*} page 页码
   * @param {*} size 分页大小
   * @param {*} sort 排序
   * @param {*} filter 过滤数据
   * @return {Array}
   */  
  async getList (json = {}, page = 1, size = 15, sort = {_id: -1}, filter = {}) {
    let list = await this.find(json, filter).sort(sort).skip((page - 1) * size).limit(size);
    let count = await this.find(json).count();
    
    return {
      list,
      page: {page, size, count}
    };
  }
}